import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})
// 响应拦截器
service.interceptors.response.use((response) => {
  // 1.将axios返回的数据解一层壳
  const res = response.data
  // 2.同意处理错误的响应
  const { message, success } = res
  if (!success) {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
  Message.success(message)
  return res
}, (error) => {
  if (error.response.status === 401 && error.response.data.code === 10002) {
    Message.error(error.response.data.message)
    store.dispatch('user/logout')
    router.push('/login')
  }
  return Promise.reject(error)
})
// 请求拦截器
service.interceptors.request.use(function(config) {
  // 携带token
  const token = store.getters.token

  config.headers.Authorization = 'Bearer ' + token

  return config
}, function(error) {
  return Promise.reject(error)
})

export default service
